﻿using AutoMapper;
using Ducu.BLL.Entity;
using Ducu.GLB.Global;
using Ducu.SRV.Query;
using Ducu.SRV.ServiceInteface;
using Ducu.SRV.ViewModel.Message;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Ducu.SRV.ProdService
{
    public class MessageService : BaseService, IMessageService
    {
        public bool HasNew()
        {
            return repoFactory.Query<Message>()
                .New(getCurrentUser()).Count() > 0;
        }

        public int GetToMeCount()
        {
            return repoFactory.Query<Message>().Get(getCurrentUser())
                .Count();
        }
        
        IndexModel IMessageService.GetToMe(Pager pager)
        {
            return new IndexModel
            {
                Items = Mapper.Map<IList<ItemModel>>(
                    repoFactory.Query<Message>().Get(getCurrentUser())
                    .OrderBy(m => m.HasRead)
                    .ThenByDescending(m => m.CreateTime)
                    .Page(pager))
            };
        }

        public void Read(int id)
        {
            Message message = repoFactory.Load<Message>(id);
            message.HasRead = true;
        }


        public IndexModel GetFromMe(Pager pager)
        {
            return new IndexModel
            {
                Items = Mapper.Map<IList<ItemModel>>(
                    repoFactory.Query<Message>().GetFrom(getCurrentUser())
                    .OrderBy(m => m.HasRead)
                    .ThenByDescending(m => m.CreateTime))
            };
        }


        public void SendFromMe(string content, int toId)
        {
            User me = getCurrentUser();
            User to = repoFactory.Load<User>(toId);

            Chat chat = new Chat
            {
                Content = content,
                From = me,
                To = to
            };

            Message message = chat.GetMessage();

            repoFactory.Save<Chat>(chat);
            repoFactory.Save<Message>(message);
        }
    }
}
